package cn.zf233.xcloud.util;

import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.Map;

/**
 * Created by zf233 on 2021/2/19
 * 腾讯防水墙工具类
 */
public class KaptchaUtil {

    private String APP_ID;
    private String APP_SECRET;

    public Integer test(String ticket, String randstr, HttpServletRequest request) {
        String userIp = CommonUtil.getRealIp(request);
        CloseableHttpClient httpclient = HttpClients.createDefault();
        HttpGet httpGet;
        CloseableHttpResponse response = null;
        try {
            final String verifyUrl = "https://ssl.captcha.qq.com/ticket/verify?aid=%s&AppSecretKey=%s&Ticket=%s&Randstr=%s&UserIP=%s";
            httpGet = new HttpGet(String.format(verifyUrl,
                    APP_ID,
                    APP_SECRET,
                    URLEncoder.encode(ticket, StandardCharsets.UTF_8.name()),
                    URLEncoder.encode(randstr, StandardCharsets.UTF_8.name()),
                    URLEncoder.encode(userIp, StandardCharsets.UTF_8.name())
            ));
            response = httpclient.execute(httpGet);
            HttpEntity entity = response.getEntity();
            if (entity != null) {
                String res = EntityUtils.toString(entity);
                Map result = JsonUtil.toObject(res);
                if (result != null) {
                    int code = Integer.parseInt(result.get("response").toString());
                    if (code == 1) {
                        return code;
                    }
                }
                return -1;
            }
        } catch (java.io.IOException e) {
            // 忽略
        } finally {
            if (response != null) {
                try {
                    response.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return -1;
    }

    public void setAPP_ID(String APP_ID) {
        this.APP_ID = APP_ID;
    }

    public void setAPP_SECRET(String APP_SECRET) {
        this.APP_SECRET = APP_SECRET;
    }
}